import pygtk
pygtk.require("2.0")
import gtk


class LogView(gtk.ScrolledWindow):

    def __init__(self):
        gtk.ScrolledWindow.__init__(self)
        # Scrollbars -- Horizontal never, vertical always.
        self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_ALWAYS)

        # Create textview to hold log text.
        self.textview = gtk.TextView()
        self.textview.set_editable(False)
        self.textview.set_wrap_mode(gtk.WRAP_WORD)
        self.textview.show()
        # Get a handle on the textview's buffer.
        self.buffer = self.textview.get_buffer()
        # Create the mark we'll use to keep cursor at most recent message.
        self.mark = self.buffer.create_mark(
            'Newest', self.buffer.get_end_iter())

        self.add(self.textview)

        # Background colors for highlighting messages.
        self.colors = {
            'success': '#33CC33', # green
            'error': '#FF6666', # red
            'warning': '#FFCC33', # yellow-orange
        }

        # Create a "tag" for each background color.
        self.tags = {}
        tagTable = self.buffer.get_tag_table()
        for name, color in self.colors.items():
            tag = gtk.TextTag()
            tag.set_property('paragraph-background', color)
            tagTable.add(tag)
            self.tags[name] = tag

    def log(self, message, status=None):
        """Adds a message to the LogView control."""
        # Get text from textview.
        text = self.buffer.get_text(
            self.buffer.get_start_iter(),
            self.buffer.get_end_iter())
        # Start a new line if non-empty.
        if len(text) != 0:
            self.buffer.insert(self.buffer.get_end_iter(), '\n')
        # Have a tag to apply?
        if status is None:
            tag = None
        else:
            try:
                tag = self.tags[status]
            except KeyError:
                tag = None
        # Append message.
        if tag is None:
            # Print plain line.
            self.buffer.insert(self.buffer.get_end_iter(), message)
        else:
            # Stylize the line.
            self.buffer.insert_with_tags(
                self.buffer.get_end_iter(), message, tag)
        # Scroll to current status.
        self.buffer.move_mark(self.mark, self.buffer.get_end_iter())
        self.textview.scroll_mark_onscreen(self.mark)

    def clear(self):
        self.buffer.set_text('')
        self.buffer.move_mark(self.mark, self.buffer.get_end_iter())


